import { ElMessage, ElMessageBox } from 'element-plus'
import { post } from "/src/api/index";
import { ref, unref, watch, onMounted } from 'vue'
import { getSelection, batchUpdateValue,fireExecute, sdp_language_project_extra_info } from '/src/utils/index'
import { sortObject } from '/src/utils/index'

export function init(self) {
  const module = self.module.value
  self.title = ref('project')
  self.extra_info_columns = sdp_language_project_extra_info.filter(ele => ele.label!='==')
  self.custom = {
    columns : [
      {
        prop: 'id',
        hide: true,
      },
      {
        prop: 'workspace_name',
        order: 'asc',
        label: '工作区',
        width: 150,
      },
      {
        prop: 'group_name',
        order: 'asc',
        label: '组名称',
        width: 100,
      },
      {
        prop: 'name',
        order: 'asc',
        label: '名称',
        width: 400,
      },
      {
        prop: 'tables',
        label: '表',
        width: 400,
      },
      {
        prop: 'root_path',
        label: '路径',
        width: 300,
      },
      {
        prop: 'extra_info',
        width: 100,
      },
      ...self.extra_info_columns.map(ele => {
        return {
          ...ele,
          prop: 'extra_info_'+ele.prop,
          width: 100,
        }
      }),
      {

      },
    ],

    editColumns : [
      {
        prop: 'id',
        hide: true,
      },
      {
        prop: 'workspace_name',
        label: '工作区',
        list_remote: {
          module: 'sdp_workspace', method:'list',
          query: {},
          sortInfo: ['name'],
          mapInfo: {label:'name', value:'name'}
        },
        type: 'select',
        required: true,
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if (mode.indexOf('init') < 0) {
          }
        },
      },
      {
        prop: 'group_name',
      },
      {
        prop: 'name',
        required: true,
      },
      {
        prop: 'tables',
        type: 'textarea',
        rows: 8,
        onclick: param => {
          let txt = unref(unref(self).editDialogInfo).form.tables
          let target = param.srcElement
          if('selectionStart' in target) {
            let leftStr = txt.substr(0, target.selectionStart)
            let line = leftStr.split(',').length-1
            let array =  txt.split(',')
            let leftKey = array[line].split(' as ')[0]
            leftKey = leftKey.trim()
            if(leftKey) {
              let extra_info = JSON.parse(unref(unref(self).editDialogInfo).form.extra_info)
              unref(unref(self).editDialogInfo).form.extra_info_common_table__t = leftKey
              // unref(unref(self).editDialogInfo).form.extra_info_common_table__v = extra_info[leftKey]
            }
          }
        },
      },
      {
        prop: 'extra_info_common_table_',
        label: '表通用扩展属性',
        type: 'extra_info_common_table_',
        buttons: [
          {
            label: '删除',
            onclick: param => {
              let {form} = param
              if(form.extra_info_common_table__k && form.extra_info_common_table__t) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                delete extra_info['_table_'+form.extra_info_common_table__t+';'+form.extra_info_common_table__k]
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              } else if(form.extra_info_common_table__t) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                for(let p in extra_info) {
                  if(p.indexOf('_table_'+form.extra_info_common_table__t+';') == 0) {
                    if(form.extra_info_common_table__v == extra_info[p]) {
                      delete extra_info[p]
                    } else if(!form.extra_info_common_table__v && form.extra_info_common_table__v !== '0'){
                      delete extra_info[p]
                    }
                  }
                }
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              }
            }
          },
          {
            label: '新增',
            onclick: param => {
              let {form} = param
              if(form.extra_info_common_table__k && form.extra_info_common_table__t) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                extra_info['_table_'+form.extra_info_common_table__t+';'+form.extra_info_common_table__k] = form.extra_info_common_table__v
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              }
            }
          },
        ],
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if (mode.indexOf('init') < 0) {
            if(form.extra_info_common_table__t && form.extra_info_common_table__k) {
              let extra_info = JSON.parse(form.extra_info||'{}')
              extra_info['_table_'+form.extra_info_common_table__t+';'+form.extra_info_common_table__k] = form.extra_info_common_table__v
              
              form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
            }
          }
        },
      },
      {
        prop: 'extra_info',
        type: 'textarea',
        rows: 5,
        onclick: param => {
          let txt = unref(unref(self).editDialogInfo).form.extra_info
          let target = param.srcElement
          if('selectionStart' in target) {
            let leftStr = txt.substr(0, target.selectionStart)
            let line = leftStr.split('\n').length-1
            let array =  txt.split('\n')
            let leftKey = array[line].split(':')[0]
            leftKey = JSON.parse(leftKey)
            if(leftKey) {
              let extra_info = JSON.parse(unref(unref(self).editDialogInfo).form.extra_info)
              if(leftKey.indexOf('_table_') == 0) {
                unref(unref(self).editDialogInfo).form.extra_info_common_table__t = leftKey.substring('_table_'.length).split(';')[0]
                unref(unref(self).editDialogInfo).form.extra_info_common_table__k = leftKey.substring('_table_'.length).split(';')[1]
                unref(unref(self).editDialogInfo).form.extra_info_common_table__v = extra_info[leftKey]
              } else {
                unref(unref(self).editDialogInfo).form.extra_info_common__k = leftKey
                unref(unref(self).editDialogInfo).form.extra_info_common__v = extra_info[leftKey]
              }
            }
          }
        },
      },
      {
        prop: 'extra_info_common_',
        label: '通用扩展属性',
        type: 'extra_info_common_',
        buttons: [
          {
            label: '删除',
            onclick: param => {
              let {form} = param
              if(form.extra_info_common__k) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                delete extra_info[form.extra_info_common__k]
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              }
            }
          },
          {
            label: '新增',
            onclick: param => {
              let {form} = param
              if(form.extra_info_common__k) {
                let extra_info = JSON.parse(form.extra_info||'{}')
                extra_info[form.extra_info_common__k] = form.extra_info_common__v
                form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
              }
            }
          },
        ],
        onchange: param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          if (mode.indexOf('init') < 0) {
            if(form.extra_info_common__k) {
              let extra_info = JSON.parse(form.extra_info||'{}')
              extra_info[form.extra_info_common__k] = form.extra_info_common__v
              form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
            }
          }
        },
      },
      ...self.extra_info_columns.map(ele => {
        let onchange = param => {
          let {mode, form, column, columns, get_remote_list, set_query_storage} = param
          let extra_info
          if (form.extra_info) {
            extra_info = JSON.parse(form.extra_info)
          } else {
            extra_info = {}
          }
          let prop = column.prop.substring('extra_info_'.length)
          if (form[column.prop]) {
            extra_info[prop] = form[column.prop]
          } else {
            delete extra_info[prop]
          }
          form.extra_info = JSON.stringify(sortObject(extra_info), null, 2)
        }
  
        if (ele.prop.indexOf('is_') >= 0) {
          return {
            ...ele,
            prop: 'extra_info_'+ele.prop,
            type: 'switch',
            onchange,
          }
        }
        return {
          ...ele,
          prop: 'extra_info_'+ele.prop,
          onchange,
        }
      }),
      {

      },
    ],

    queryColumns : [
      {
        prop: 'workspace_name',
        fixed: true,
        list_remote: {
          module: 'sdp_workspace', method:'list',
          query: {},
          sortInfo: ['name'],
          mapInfo: {label:'name', value:'name'}
        },
        type: 'select',
      },
      {
        prop: 'group_name_like',
        label: '组名称',
        width: '100px',
      },
      {
        prop: 'name_like',
        label: '名称',
        width: '150px',
      },
      {
        prop: 'tables_like',
        label: '表',
        width: '150px',
      },
      {
        prop: 'root_path_like',
        label: '路径',
        width: '150px',
      },
    ],

    buttons: [
      {
        prop: 'fireExecute',
        label: '生成文件',
        loading: false,
        type: 'success',
        onclick: (param) => {
          fireExecute({param, self})
        }
      },
      {
        prop: 'fireExecuteAi',
        label: '生成文件(ai)',
        loading: false,
        onclick: (param) => {
          fireExecute({param, self, isAi:true})
        }
      },
      {
        prop: 'setTables',
        label: '设置表及别名',
        loading: false,
        onclick: (param) => {
          let {setTablesDialogInfo : dialogInfo, selectRows} = self
          dialogInfo = unref(dialogInfo)
          selectRows = unref(selectRows)
          if (!selectRows || selectRows.length == 0) {
            ElMessage.error(`请选择至少一条记录后再操作`);
            return;
          }

          selectRows = unref(selectRows)
          let item = selectRows[0]
          post('sdp_workspace', 'get_table_list', {workspace_name: item.workspace_name})
          .then( data => {
            console.log('data', data)
            let notInclude = 0
            dialogInfo.columns = data.map(ele => {
              let isGenerate
              if(ele.name.indexOf('-') > 0 && ele.name.indexOf('tables not include') < 0) {
                isGenerate = ele.name.split('-')[1]
              } else if (ele.alias_name && ele.alias_name.indexOf('-') > 0 && ele.alias_name.indexOf('tables not include') < 0) {
                isGenerate = ele.alias_name.split('-')[1]
              }
              if(ele.name.indexOf('tables not include') < 0) {
                ele.name = ele.name.split('-')[0]
              }
              if(ele.alias_name && ele.alias_name.indexOf('tables not include') < 0) {
                ele.alias_name = ele.alias_name.split('-')[0]
              }
              if(isGenerate) {
                console.log('isGenerate', ele.name, ele.alias_name, ele)
                item[ele.name+'_active'] = 1
                item[ele.name+'_ignore_no_generate'] = 1
              }
              if (notInclude) {
                if(!item[ele.name+'_active']) {
                  item[ele.name+'_active'] = 0
                }
                return {
                  prop: ele.name,
                  alias: ele.alias_name,
                  isGenerate: isGenerate,
                  label: ele.remark || ele.name,
                  type: 'project_table',
                  onchange: param => {
                    let {mode, form, column, columns, get_remote_list, set_query_storage, extra_column_name} = param
                    form = unref(form)
                    console.log('form', form)
                    column = unref(column)
                    console.log('column', column)
                    if (mode.indexOf('init') < 0) {
                      console.log('onchange', mode, form, column, form[column.name], extra_column_name)
                      console.log('onchange', column.prop+'_'+extra_column_name, form[column.prop+'_'+extra_column_name])
                      if(form[column.prop+'_'+extra_column_name] && extra_column_name != 'active') {
                        form[column.prop+'_active'] = 1
                      }
                      if(extra_column_name == 'active' && !form[column.prop+'_'+extra_column_name]) {
                        form[column.prop+'_ignore_no_generate'] = 0
                      }
                    }
                  },
                }
              }
              if (ele.name.indexOf('tables not include') >= 0) {
                notInclude = 1
              } else {
                item[ele.name+'_active'] = 1
                if (ele.alias_name) {
                  item[ele.name+'_alias'] = ele.alias_name
                }
              }
              return {
                prop: ele.name,
                alias: ele.alias_name,
                isGenerate: isGenerate,
                label: ele.remark || ele.name,
                type: 'project_table',
                active: 1,
                onchange: param => {
                  let {mode, form, column, columns, get_remote_list, set_query_storage} = param
                  if (mode.indexOf('init') < 0) {
                    console.log('onchange', mode, form, column, form[column.name])
                  }
                },
              }
            }).filter(ele => ele.prop.indexOf('tables not include') < 0)
            dialogInfo.columns = dialogInfo.columns.sort((a,b) => {
              let n1 = a.active ? '0' : '1';
              let n2 = b.active ? '0' : '1';
              n1 += a.isGenerate ? '0' : '1';
              n2 += b.isGenerate ? '0' : '1';
              n1 += ';'+(a.alias || a.prop)
              n2 += ';' + (b.alias || b.prop)
              return n1.localeCompare(n2)
            })
            dialogInfo.form = {...item}
            console.log('dialogInfo.form', dialogInfo.form, dialogInfo.columns)
            dialogInfo.form_ori = {...item}
            dialogInfo.show({...param, dialogInfo})
          })
        }
      },
      {
        prop: 'batchEdit',
        label: '批量编辑',
        loading: false,
        onclick: (param) => {
          let {batchEditDialogInfo : dialogInfo, selectRows} = self
          dialogInfo = unref(dialogInfo)
          selectRows = unref(selectRows)
          if (!selectRows || selectRows.length == 0) {
            ElMessage.error(`请选择至少一条记录后再操作`);
            return;
          }

          selectRows = unref(selectRows)
          let item = selectRows[0]
          dialogInfo.form = {...item}
          dialogInfo.form_ori = {...item}
          dialogInfo.show({...param, dialogInfo})
        }
      },
      {
        prop: 'setRootPath',
        label: '设置(root)目录',
        loading: false,
        onclick: (param) => {
          let {editDialogInfo : dialogInfo, selectRows} = self
          selectRows = unref(selectRows)
          if (!selectRows || selectRows.length == 0) {
            let query = unref(self.query)
            if (query.workspace_name) {
              selectRows = unref(self.tableData)
            }
          }
          if (!selectRows || selectRows.length == 0) {
            ElMessage.error(`请选择至少一条记录后再操作`);
            return;
          }

          let item = selectRows[0]
          let foundItem = selectRows.filter(ele => ele.root_path.indexOf('(root)') >= 0)
          if (!foundItem || !foundItem.length) {
            ElMessage.error(`请选择至少一条未设置root目录的记录后再操作`);
            return;
          }

          ElMessageBox.prompt('请输入(root)目录', '设置(root)目录', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            closeOnPressEscape:false,
            closeOnClickModal:false,
            inputValidator: (val) => {
              if (val === null||val.length < 1) {
                return false;
              }
            },
            inputErrorMessage: '此项不能为空',
          })
            .then(({ value }) => {
              if (!value) {
                return;
              }
              while (value.substring(value.length - 1) == '/') {
                value = value.substring(0, value.length - 1)
              }
              while (value.substring(value.length - 1) == '\\') {
                value = value.substring(0, value.length - 1)
              }
              if (!value) {
                return;
              }
              dialogInfo.loading = true
              let count = 0
              foundItem.forEach( ele => {
                let form = {id:ele.id, root_path:ele.root_path.replace('(root)', value)}
                post('sdp_project', 'update', form)
                .then((data) => {
                  count++
                  if (count == foundItem.length) {
                    dialogInfo.loading = false
                    ElMessage.success('更新成功')
                    self.handleSearch()
                  }
                })
                .catch((err) => {
                  dialogInfo.loading = false
                  ElMessage.error(`无法更新，错误：${ex}`);
                })
              })
            })
            .catch(() => {
            })

        }
      },
    ],

    remoteConfig : {
    },

    onInit: () => {
      self.handleSearch_ori = self.handleSearch
      self.handleSearch = (param) => {
        return self.handleSearch_ori(param)
        .then( data => {
          unref(self.tableData).forEach( ele => {
            if (ele.extra_info) {
              let j = JSON.parse(ele.extra_info)
              for(let p in j) {
                ele['extra_info_'+p] = j[p]
              }
            }
          })
          return data;
        })
      }

      self.cellMouseEnter = (row, column, cell, event) => {
        if (column && column.property == 'tables') {
          // self.whiteSpace.value = 'pre-line'
        }
      }
      self.cellMouseLeave = (row, column, cell, event) => {
        // self.whiteSpace.value = 'nowrap'
      }
    },

  }
}

